#!/usr/bin/python
# -*- coding: utf-8 -*-

from GameRunner import GameRunner
from optparse import OptionParser
import GameRunner
import dbhash
import os.path
import string
import sys
import time
import traceback
import urllib2
import winshell
import wx
import wx.calendar
import wx.grid
import wx.lib.mixins.listctrl as listmix

#-----------------------------------------------------------------------------
# Name:        
# Purpose:     
#
# Author:      Administrator
#
# Created:     2006-10-21 下午04:31:06
# RCS-ID:      Id:  
# Copyright:   (c) 2006
# Licence:     Free To Use
# 
#-----------------------------------------------------------------------------

#FIXME: swig/python detected a memory leak of type 'wxPasswordEntryDialog *', no destructor found.

#import win32con
#import win32ui

#------------------------------------------------------------------------------ 
# Config Var
__DATE__ = "$Date: 2006-12-21 18:02:58 +0800 (Thu, 21 Dec 2006) $"

__MINO_VERSION__ = "$Rev: 707 $"

__VERSION__ = "0.1."+__MINO_VERSION__.split()[1]

__INIT_URL__ = 'http://lic.rorer.org/glinit'

__ABOUT_URL__ = 'http://gameloadermaster.googlepages.com/home'

__SHOW_GUI__ = True

class GameLoaderConfig:
    
    def __init__( self ):
        '''read db file , return all parm
            if db file error , then create a db file
        '''
        self.ACCT_LIST_INFO = {0:['---', '---']}
        self.SRV_LIST_INFO = {0:['---', '---', '---', '---']}
        self.GL_LOG = []
        self.ADMIN_PASS = "123456"
        
        # Program status var
        self.LOAD_CONFIG_STAT = True
        self.SELECTED_ACCT = 0
        self.SELECTED_PROXY = 0
        
        self.fdb = dbhash.open( 'glc.dat', 'w' )
        
        if self.load_from_config_file() :
            pass
        else:
            self.LOAD_CONFIG_STAT = False
            
    def init_config_file( self ):
        '''create a init pickle file
        
        '''
        #TAG: We need check init word, if database Error
        self.fdb = dbhash.open( 'glc.dat', 'c' )
        
        self.fdb['admin_pass'] = self.ADMIN_PASS
        self.fdb['gl_log'] = str( self.GL_LOG )
        self.fdb['acct_list_info'] = str( self.ACCT_LIST_INFO )
        self.fdb['srv_list_info'] = str( self.SRV_LIST_INFO )
        
        self.sync_to_config_file()        
        
        self.load_from_config_file()
    
    def load_from_config_file( self ):
        '''reload pick file
        '''
        
        try:
            self.ADMIN_PASS = self.fdb['admin_pass']
        except KeyError:
            return False
            
        try:
            self.ACCT_LIST_INFO = eval( self.fdb['acct_list_info'] )
        except KeyError:
            return False
            
        try:
            self.SRV_LIST_INFO = eval( self.fdb['srv_list_info'] )
        except KeyError:
            return False
    
        return True

    def sync_to_config_file( self ):
        ''' sync db 
        '''
        self.fdb.sync()
    
    def close_config_file( self ):
        '''Close dbm file
        '''
        
        self.fdb.close()
        
    def set_log( self, s ):
        '''write a log str into dbm file
        
        @param s:
        '''
        _now_time = time.ctime() 
        self.GL_LOG.append( '%s - %s ' % ( _now_time, s ) )
        self.fdb['gl_log'] = str( self.GL_LOG )
        self.sync_to_config_file()
        
    def get_log( self ):
        
        return eval( self.fdb['gl_log'] )
    
    def get_admin_pass( self ):
        '''return admin pass
        '''
        
        return self.ADMIN_PASS
    
    def set_admin_pass( self, pw ):
        '''set admin password
        
        @param pw:
        '''
        
        try:
            self.ADMIN_PASS = pw
            self.fdb['admin_pass'] = pw
            self.sync_to_config_file()
            return True
        except:
            return False
        
    
    def get_acct_info( self, acct_id=None ):
        ''' return account info
        '''
        if acct_id == None:
            return self.ACCT_LIST_INFO
        else:
            try:
                return self.ACCT_LIST_INFO[acct_id]
            except KeyError:
                return None
    
    def set_acct_info( self, acct_data ):
        '''set account info
        '''
        self.ACCT_LIST_INFO = acct_data
        self.fdb['acct_list_info'] = str( acct_data )
        self.sync_to_config_file()
        return 
    
    def get_srv_info( self, srv_id=None ):
        '''return server list info
        '''
        if srv_id == None:
            return self.SRV_LIST_INFO
        else:
            try :
                return self.SRV_LIST_INFO[srv_id]
            except KeyError:
                return None
    
    def set_srv_info( self, srv_data ):
        '''set server list info
        '''
        
        self.SRV_LIST_INFO = srv_data
        self.fdb['srv_list_info'] = str( srv_data )
        self.sync_to_config_file()
        return 
    
class ShowLogDialog( wx.Dialog ):
    '''show program running log
    '''
    
    def __init__( self, *args, **kwds ):
        # begin wxGlade: ShowLogDialog.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX
        wx.Dialog.__init__( self, *args, **kwds )
        self.panel_1 = wx.Panel( self, -1 )
        self.log_text = wx.TextCtrl( self, -1, "", \
                                    style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL|wx.TE_RICH|wx.TE_RICH2|wx.TE_AUTO_URL|wx.TE_WORDWRAP )
        self.clean_log_button = wx.Button( self.panel_1, -1, "&Clean Log" )
        self.exit_show_log_button = wx.Button( self.panel_1, -1, "&Exit" )

        self.__set_properties()
        self.__do_layout()
        # end wxGlade
        
        #--- bind show log event
        self.Bind( wx.EVT_BUTTON, self.EvtExitButton, self.exit_show_log_button )

    def __set_properties( self ):
        # begin wxGlade: ShowLogDialog.__set_properties
        self.SetTitle( "Show Program Running Log" )
        self.SetSize( wx.DLG_SZE( self, ( 334, 237 ) ) )
        self.log_text.SetMinSize( wx.DLG_SZE( self.log_text, ( 334, 200 ) ) )
        self.log_text.SetFont( wx.Font( 8, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "" ) )
        self.exit_show_log_button.SetDefault()
        for x in gl_options.get_log():
            self.log_text.AppendText( x )
        # end wxGlade

    def __do_layout( self ):
        # begin wxGlade: ShowLogDialog.__do_layout
        grid_sizer_1 = wx.FlexGridSizer( 2, 1, 2, 2 )
        grid_sizer_2 = wx.FlexGridSizer( 1, 3, 2, 2 )
        grid_sizer_1.Add( self.log_text, 0, \
                         wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 0 )
        grid_sizer_2.Add( ( 180, 20 ), 0, wx.ADJUST_MINSIZE, 0 )
        grid_sizer_2.Add( self.clean_log_button, 0, wx.ADJUST_MINSIZE, 0 )
        grid_sizer_2.Add( self.exit_show_log_button, 0, wx.ALL|wx.ADJUST_MINSIZE, 0 )
        self.panel_1.SetAutoLayout( True )
        self.panel_1.SetSizer( grid_sizer_2 )
        grid_sizer_2.Fit( self.panel_1 )
        grid_sizer_2.SetSizeHints( self.panel_1 )
        grid_sizer_1.Add( self.panel_1, 1, wx.EXPAND, 0 )
        self.SetAutoLayout( True )
        self.SetSizer( grid_sizer_1 )
        self.Layout()
        self.Centre()
        # end wxGlade
    
    def EvtExitButton( self, evt ):
        self.Close()


class AcctListCtrl( wx.ListCtrl, 
                   listmix.ListCtrlAutoWidthMixin, 
                   listmix.TextEditMixin ):
    def __init__( self, parent, ID, pos=wx.DefaultPosition, 
                 size=wx.DefaultSize, style=0 ):
        wx.ListCtrl.__init__( self, parent, ID, pos, size, style )

        listmix.ListCtrlAutoWidthMixin.__init__( self )
        self.Populate()
        listmix.TextEditMixin.__init__( self )
        
        self.Bind( wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick )

    def Populate( self ):
        # for normal, simple columns, you can add them like this:
        self.InsertColumn( 0, "Account Name" )
        self.InsertColumn( 1, "Account Passwd" )

        #items = ACCOUNTLISTDATA.items()
        items = gl_options.get_acct_info().items()
        for key, data in items:
            index = self.InsertStringItem( sys.maxint, data[0] )
            self.SetStringItem( index, 0, data[0] )
            self.SetStringItem( index, 1, data[1] )
            self.SetItemData( index, key )

        self.SetColumnWidth( 0, 200 )
        self.SetColumnWidth( 1, 200 )

        #self.currentItem = 0
    
        #self.Append(['OK', 'bad'])
    
    def OnRightClick( self, evt ):
        if not hasattr( self, "add_acct_popup_menu" ):
            self.add_acct_popup_menu = wx.NewId()
            self.del_acct_popup_menu = wx.NewId()

            self.Bind( wx.EVT_MENU, self.OnAppendAccount, \
                      id=self.add_acct_popup_menu )
            self.Bind( wx.EVT_MENU, self.OnDeleteAccount, \
                      id=self.del_acct_popup_menu )
            
        # make a menu
        menu = wx.Menu()
        # add some items
        menu.Append( self.add_acct_popup_menu, "Add Account" )
        menu.Append( self.del_acct_popup_menu, "Del Account" )

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu( menu )
        menu.Destroy()
        
    def OnAppendAccount( self, evt ):
        self.Append( ['---', '---'] )
    
    def OnDeleteAccount( self, evt ):
        i = self.GetFocusedItem()
        if i == -1:
            pass
        else:
            if self.IsSelected( i ):
                self.DeleteItem( i )
            else:
                pass
        return


class ProxytListCtrl( wx.ListCtrl, 
                   listmix.ListCtrlAutoWidthMixin, 
                   listmix.TextEditMixin ):
    def __init__( self, parent, ID, pos=wx.DefaultPosition, 
                 size=wx.DefaultSize, style=0 ):
        wx.ListCtrl.__init__( self, parent, ID, pos, size, style )

        listmix.ListCtrlAutoWidthMixin.__init__( self )
        self.Populate()
        listmix.TextEditMixin.__init__( self )
        
        self.Bind( wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick )

    def Populate( self ):
        # for normal, simple columns, you can add them like this:
        self.InsertColumn( 0, "Proxy Address" )
        self.InsertColumn( 1, "Proxy Port" )
        self.InsertColumn( 2, "Proxy Username" )
        self.InsertColumn( 3, "Proxy Password" )

        #items = SERVERLISTDATA.items()
        items = gl_options.get_srv_info().items()
        for key, data in items:
            index = self.InsertStringItem( sys.maxint, data[0] )
            self.SetStringItem( index, 0, data[0] )
            self.SetStringItem( index, 1, data[1] )
            self.SetStringItem( index, 2, data[2] )
            self.SetStringItem( index, 3, data[3] )
            self.SetItemData( index, key )

        self.SetColumnWidth( 0, 120 )
        self.SetColumnWidth( 1, 80 )
        self.SetColumnWidth( 2, 120 )
        self.SetColumnWidth( 3, 120 )

        self.currentItem = 0
    
        #self.Append(['OK', 'bad'])
    
    def OnRightClick( self, evt ):
        if not hasattr( self, "add_proxy_popup_menu" ):
            self.add_proxy_popup_menu = wx.NewId()
            self.del_proxy_popup_menu = wx.NewId()

            self.Bind( wx.EVT_MENU, self.OnAddProxy, id=self.add_proxy_popup_menu )
            self.Bind( wx.EVT_MENU, self.OnDelProxy, id=self.del_proxy_popup_menu )
            
        # make a menu
        menu = wx.Menu()
        # add some items
        menu.Append( self.add_proxy_popup_menu, "Add Proxy" )
        menu.Append( self.del_proxy_popup_menu, "Delete Proxy" )

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu( menu )
        menu.Destroy()
        
    def OnAddProxy( self, evt ):
        self.Append( ['---', '---', '---', '---'] )
    
    def OnDelProxy( self, evt ):
        i = self.GetFocusedItem()
        if i == -1:
            pass
        else:
            if self.IsSelected( i ):
                self.DeleteItem( i )
            else:
                pass
        return

class OptNotebook( wx.Notebook ):
    def __init__( self, *args, **kwds ):
        # begin wxGlade: OptNotebook.__init__
        kwds["style"] = 0
        wx.Notebook.__init__( self, *args, **kwds )
        self.proxy_info_pane = wx.Panel( self, -1 )
        self.acct_info_pane = wx.Panel( self, -1 )
        self.admin_pass_pane = wx.Panel( self, -1 )
        self.admin_pass_lable = wx.StaticText( self.admin_pass_pane, -1, "Admin Password:" )
        self.admin_pass_text = wx.TextCtrl( self.admin_pass_pane, -1, "", style=wx.TE_PASSWORD )
        self.re_admin_pass_lable = wx.StaticText( self.admin_pass_pane, -1, "Re Admin Password:" )
        self.re_admin_pass_text = wx.TextCtrl( self.admin_pass_pane, -1, "", style=wx.TE_PASSWORD )
        self.apply_admin_pass_button = wx.Button( self.admin_pass_pane, -1, "Apply Admin Password Setting" )
        
        # replace with AccountListCtrl
        self.acct_list_ctrl = AcctListCtrl( self.acct_info_pane, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL )
        
        self.apply_acct_setting_button = wx.Button( self.acct_info_pane, -1, "Apply Account Setting " )
        self.create_shortcut_on_desktop_button = wx.Button( self.acct_info_pane, -1, "Create Shortcut On Desktop" )
        
        self.proxy_list_ctrl = ProxytListCtrl( self.proxy_info_pane, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL )
        self.apply_proxy_setting_button = wx.Button( self.proxy_info_pane, -1, "Apply Proxy Setting" )

        self.__set_properties()
        self.__do_layout()
        # end wxGlade
        
        # --- bind apply button evt
        self.Bind( wx.EVT_BUTTON, self.OnApplyAcctSettingButton, self.apply_acct_setting_button )
        self.Bind( wx.EVT_BUTTON, self.OnApplyProxySettingButton, self.apply_proxy_setting_button )
        self.Bind( wx.EVT_BUTTON, self.OnApplyAdminPassSettingButton, self.apply_admin_pass_button )
        self.Bind( wx.EVT_BUTTON, self.OnCreateShortcutButton, self.create_shortcut_on_desktop_button )

    def __set_properties( self ):
        # begin wxGlade: OptNotebook.__set_properties
        self.AddPage( self.admin_pass_pane, "Admin Password" )
        self.AddPage( self.acct_info_pane, "Account Info" )
        self.AddPage( self.proxy_info_pane, "Proxy Info" )
        self.admin_pass_text.SetMinSize( wx.DLG_SZE( self.admin_pass_text, ( 122, 12 ) ) )
        self.re_admin_pass_text.SetMinSize( wx.DLG_SZE( self.re_admin_pass_text, ( 122, 12 ) ) )
        self.apply_admin_pass_button.SetDefault()
        self.acct_list_ctrl.SetMinSize( wx.DLG_SZE( self.acct_list_ctrl, ( 290, 134 ) ) )
        self.proxy_list_ctrl.SetMinSize( wx.DLG_SZE( self.proxy_list_ctrl, ( 290, 150 ) ) )
        # end wxGlade

    def __do_layout( self ):
        # begin wxGlade: OptNotebook.__do_layout
        grid_sizer_3 = wx.FlexGridSizer( 2, 1, 2, 2 )
        grid_sizer_1 = wx.FlexGridSizer( 2, 1, 2, 2 )
        grid_sizer_2 = wx.FlexGridSizer( 3, 2, 2, 2 )
        grid_sizer_2.Add( self.admin_pass_lable, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 1 )
        grid_sizer_2.Add( self.admin_pass_text, 0, wx.ALL|wx.EXPAND|wx.ALIGN_RIGHT, 1 )
        grid_sizer_2.Add( self.re_admin_pass_lable, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 1 )
        grid_sizer_2.Add( self.re_admin_pass_text, 0, wx.ALL|wx.EXPAND|wx.ALIGN_RIGHT, 1 )
        grid_sizer_2.Add( self.apply_admin_pass_button, 0, wx.ALL|wx.EXPAND, 1 )
        self.admin_pass_pane.SetAutoLayout( True )
        self.admin_pass_pane.SetSizer( grid_sizer_2 )
        grid_sizer_2.Fit( self.admin_pass_pane )
        grid_sizer_2.SetSizeHints( self.admin_pass_pane )
        grid_sizer_1.Add( self.acct_list_ctrl, 1, wx.ALL|wx.EXPAND, 0 )
        grid_sizer_1.Add( self.apply_acct_setting_button, 0, wx.ALL|wx.EXPAND, 1 )
        grid_sizer_1.Add( self.create_shortcut_on_desktop_button, 0, wx.ALL|wx.EXPAND, 1 )
        self.acct_info_pane.SetAutoLayout( True )
        self.acct_info_pane.SetSizer( grid_sizer_1 )
        grid_sizer_1.Fit( self.acct_info_pane )
        grid_sizer_1.SetSizeHints( self.acct_info_pane )
        grid_sizer_3.Add( self.proxy_list_ctrl, 1, wx.EXPAND, 0 )
        grid_sizer_3.Add( self.apply_proxy_setting_button, 0, wx.ALL|wx.EXPAND, 1 )
        self.proxy_info_pane.SetAutoLayout( True )
        self.proxy_info_pane.SetSizer( grid_sizer_3 )
        grid_sizer_3.Fit( self.proxy_info_pane )
        grid_sizer_3.SetSizeHints( self.proxy_info_pane )
        # end wxGlade

    def OnApplyAdminPassSettingButton( self, evt ):
        
        pass1 = self.admin_pass_text.GetValue()
        pass2 = self.re_admin_pass_text.GetValue()
        
        if len( pass1 ) < 6 or len( pass2 ) < 6:
            dgl = wx.MessageDialog( self, 'The password length MUST over 6 letter', 'Error', style=wx.OK|wx.ICON_ERROR )
            dgl.ShowModal()
            return
        
        if pass1 == pass2 :
            gl_options.set_admin_pass( pass1 )
            dgl = wx.MessageDialog( self, 'OK, Password saved', 'Sucess', style=wx.OK )
            dgl.ShowModal()
            return
        else:
            dgl = wx.MessageDialog( self, 'Password input Error', 'Error', style=wx.OK|wx.ICON_ERROR )
            dgl.ShowModal()
            return 
    
    def OnApplyAcctSettingButton( self, evt ):
        all_index = listmix.getListCtrlSelection( self.acct_list_ctrl, state=wx.LIST_STATE_DONTCARE )
        all_data = {}
        for x in all_index:
            item_data = []
            for s in range( self.acct_list_ctrl.GetColumnCount() ):
                item_data.append( self.acct_list_ctrl.GetItem( x, s ).GetText() )
            all_data[x] = item_data

        gl_options.set_acct_info( all_data )
        dgl = wx.MessageDialog( self, 'OK, Account infomation saved\r\n\r\nNote: Please restart GameLoader', 'Sucess', style=wx.OK )
        dgl.ShowModal()
    
    def OnApplyProxySettingButton( self, evt ):
        all_index = listmix.getListCtrlSelection( self.proxy_list_ctrl, state=wx.LIST_STATE_DONTCARE )
        all_data = {}
        for x in all_index:
            item_data = []
            for s in range( self.proxy_list_ctrl.GetColumnCount() ):
                item_data.append( self.proxy_list_ctrl.GetItem( x, s ).GetText() )
            all_data[x] = item_data
        #all_data = SERVERLISTDATA
        #print all_data,'OK'
        gl_options.set_srv_info( all_data )
        dgl = wx.MessageDialog( self, 'OK, Proxy infomation saved\r\n\r\nNote: Please restart GameLoader', 'Sucess', style=wx.OK )
        dgl.ShowModal()

    def OnCreateShortcutButton( self, evt ):
        _a = gl_options.get_acct_info()
        _p = gl_options.get_srv_info()
        for x, y in [( x, y ) for x in _a for y in _p]:
            create_shell_shortcut( x, y )
        dgl = wx.MessageDialog( self, 'OK, Shortcut Create Sucess\r\n\r\n', 'Sucess', style=wx.OK )
        dgl.ShowModal()
            
# end of class OptNotebook


class OptionsDialog( wx.Dialog ):
    def __init__( self, *args, **kwds ):
        # begin wxGlade: OptionsDialog.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__( self, *args, **kwds )
        self.sizer_1_staticbox = wx.StaticBox( self, -1, "Admin Options" )
        self.opt_notebook = OptNotebook( self, -1 )

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties( self ):
        # begin wxGlade: OptionsDialog.__set_properties
        self.SetTitle( "Game Loader Options" )
        self.SetSize( wx.DLG_SZE( self, ( 302, 212 ) ) )
        self.SetFocus()
        # end wxGlade

    def __do_layout( self ):
        # begin wxGlade: OptionsDialog.__do_layout
        sizer_1 = wx.StaticBoxSizer( self.sizer_1_staticbox, wx.VERTICAL )
        sizer_1.Add( self.opt_notebook, 1, wx.ALL|wx.EXPAND, 0 )
        self.SetAutoLayout( True )
        self.SetSizer( sizer_1 )
        self.Layout()
        self.Centre()
        # end wxGlade

class GameLoaderStatusBar( wx.StatusBar ):
    def __init__( self, parent ):
        wx.StatusBar.__init__( self, parent, -1, style=wx.SB_NORMAL )

        # This status bar has three fields
#        self.SetStatusStyles(wx.wxSB_RAISED )
        self.SetFieldsCount( 4 )
        self.SetStatusWidths( [-0, -3, -3, -3] )
        self.sizeChanged = False
        self.SetStatusText( ":", 1 )
        self.SetStatusText( ":", 2 )
        self.timer = wx.PyTimer( self.Notify )
        self.timer.Start( 1000 )
        self.Notify()
        
    def set_status_bar_account( self, s ):
        if s == None:
            s = 'User Select'
        self.SetStatusText( "Account ID : %s" % str( s ), 1 )
        
    def set_status_bar_proxy( self, s ):
        if s == None:
            s = 'User Select'
        self.SetStatusText( "Proxy ID : %s" % str( s ), 2 )
    
    def Notify( self ):
        t = time.localtime( time.time() )
        st = time.strftime( "%d-%b-%Y %I:%M:%S", t )
        self.SetStatusText( st, 3 )
        
class GameLoaderFrame( wx.Frame ):    
    def __init__( self, parent, title ):
        
        # set status bar
        self.gl = wx.Frame.__init__( self, parent, -1, 'Game Loader', \
                                    wx.DefaultPosition, ( 382, 149 ), \
                                    style=wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.SIMPLE_BORDER | 0 | 0 | 0 )
        self.GlStatusBar = GameLoaderStatusBar( self )
        self.SetStatusBar( self.GlStatusBar )
        
        self.GlStatusBar.set_status_bar_account( gl_options.SELECTED_ACCT )
        self.GlStatusBar.set_status_bar_proxy( gl_options.SELECTED_PROXY )
        self.panel = wx.Panel( self, -1 )

        self.SrvlistBox = wx.StaticBox( self.panel, -1, "Server List", ( 8, 11 ), ( 265, 60 ) )
        self.SrvlistBox.SetFont( wx.Font( 8.25, wx.FONTFAMILY_DEFAULT, \
                                        wx.FONTSTYLE_NORMAL, \
                                        wx.FONTWEIGHT_NORMAL, 0, 'Microsoft Sans Serif' ) )
        self.SrvlistBox.SetCursor( wx.StockCursor( wx.CURSOR_DEFAULT ) )
        
        #read server list , and set srv list
        #self.SrvList_NO = sorted( SERVERLISTDATA.keys() )
        self.SrvList_NO = sorted( gl_options.get_srv_info().keys() )
        self.SrvListItem = ['']
        for x in self.SrvList_NO:
            self.SrvListItem.append( "Connect to Server NO. " + str( x ) )
        
        self.SrvListCB = wx.ComboBox( self.panel, -1, 'Please select a server', \
                                     wx.Point( 8, 23 ) + self.SrvlistBox.GetPosition(), \
                                     ( 250, 21 ), self.SrvListItem, style=wx.CB_READONLY )
        self.SrvListCB.SetBackgroundColour( wx.Colour( 255, 255, 255 ) )
        self.SrvListCB.SetFont( wx.Font( 8.25, wx.FONTFAMILY_DEFAULT, \
                                       wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, \
                                       0, 'Microsoft Sans Serif' ) )
        self.SrvListCB.SetCursor( wx.StockCursor( wx.CURSOR_DEFAULT ) )

        self.ConnectButton = wx.Button( self.panel, -1, 'Connect', ( 285, 16 ), ( 75, 23 ) )
        self.ConnectButton.SetFont( wx.Font( 8.25, wx.FONTFAMILY_DEFAULT, \
                                           wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, \
                                           0, 'Microsoft Sans Serif' ) )
        self.ConnectButton.SetCursor( wx.StockCursor( wx.CURSOR_DEFAULT ) )

        self.CancelButton = wx.Button( self.panel, -1, 'Cancel', ( 285, 48 ), ( 75, 23 ) )
        self.CancelButton.SetFont( wx.Font( 8.25, wx.FONTFAMILY_DEFAULT, \
                                          wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, \
                                          0, 'Microsoft Sans Serif' ) )
        self.CancelButton.SetCursor( wx.StockCursor( wx.CURSOR_DEFAULT ) )

        #--- Set Edit Menu
        self.UserMenuBar = wx.MenuBar()
        self.UserMenuEdit = wx.Menu()
        self.UserMenuEdit.Append( 101, '&Options', 'Set Game Loader options' )
        #self.UserMenuEdit.Append(102, '&Show Log', 'View log')
        self.UserMenuEdit.Append( 103, '&Exit', 'Exit Game Loader' )
        
        self.UserMenuBar.Append( self.UserMenuEdit, '&File' )
        
        #--- Set Help Menu
        self.UserMenuAbout = wx.Menu()
        self.UserMenuAbout.Append( 201, '&About Game Loader' )
        #self.UserMenuAbout.Append(202, '&Modules Info')
        self.UserMenuBar.Append( self.UserMenuAbout, '&Help' )
        self.SetMenuBar( self.UserMenuBar )
        
        #--- Bind Event
        
        # bind Select SrvList event
        self.Bind( wx.EVT_COMBOBOX, self.EvtSelectSrvComboBox, self.SrvListCB )
        
        # bind Cancel Button event
        self.Bind( wx.EVT_BUTTON, self.EvtCancelButton, self.CancelButton )
        
        # bind Connect Server button event
        self.Bind( wx.EVT_BUTTON, self.EvtConnectButton, self.ConnectButton )
        
        # bind menu show about
        self.Bind( wx.EVT_MENU, self.ShowAbout, id=201 )
        
        # bind menu option
        self.Bind( wx.EVT_MENU, self.ShowOptDialog, id=101 )
        
        # bind menu show log
        self.Bind( wx.EVT_MENU, self.ShowLogDialog, id=102 )
        
        # bind menu exit
        self.Bind( wx.EVT_MENU, self.JustExit, id=103 )
        
        # connect srv info 
        self.connect_srv = None
    
    def EvtConnectButton( self, evt ):
        if self.connect_srv == None:
            e = wx.MessageDialog( self, u'Please select a server', u'Connect Error', \
                                 wx.OK|wx.ICON_ERROR )
            e.ShowModal()
            e.Destroy()
            gl_options.SELECTED_PROXY = self.connect_srv
            self.GlStatusBar.set_status_bar_proxy( self.connect_srv )
            return False
        else:
            gl_options.SELECTED_PROXY = int( self.connect_srv )
            #TAG: running game in here
            try:
                game_runner()
            except GameRunner.GameRunnerAcctError :
                e = wx.MessageDialog( self, u'Running Game Error!!!(account)', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
                e.ShowModal()
                e.Destroy()
                
            except GameRunner.GameRunnerProxyError :
                e = wx.MessageDialog( self, u'Running Game Error!!!(Proxy)', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
                e.ShowModal()
                e.Destroy()
            except:
                print traceback.print_exc()
                

            # fixed, reset gl_options.selected_proxy to None
            self.connect_srv = None           
            gl_options.SELECTED_PROXY = self.connect_srv
            self.GlStatusBar.set_status_bar_proxy( self.connect_srv )

    def EvtSelectSrvComboBox( self, evt ):
        self.SrvListCB = evt.GetEventObject()
        try:
            self.connect_srv = evt.GetString()[-1]
        except IndexError:
            self.connect_srv = None
        self.GlStatusBar.set_status_bar_proxy( self.connect_srv )
        
    def EvtCancelButton( self, evt ):
        gl_options.close_config_file()
        sys.exit()
    
    def ShowAbout( self, evt ):
        info = wx.AboutDialogInfo()
        info.Name = "Game Loader"
        info.Version = __VERSION__
        info.Copyright = "    (c) Copyright by fla.sam 2006   "
        info.WebSite = __ABOUT_URL__
        info.Description = "This is a Game loader"
        info.Developers = (["            Fla.Sam    "])
        info.SetLicense('''Free used for Spilot, BUT This Program's Copyright is mine''')
        info.SetTranslators(["            Fla.Sam    "])
        wx.AboutBox( info )
        
    def JustExit( self, evt ):
        gl_options.close_config_file()
        sys.exit()
    
    def ShowOptDialog( self, evt ):
        evt.Skip()
        p = wx.PasswordEntryDialog( self, message=u"Give me a password", \
                                   caption=u'Input A Password', \
                                   style = wx.OK | wx.CANCEL | wx.CENTRE )
        p.ShowModal()
        _pass = p.GetValue()
        p.Close()
        if _pass == gl_options.get_admin_pass():
            gl_options.set_log( 'Admin Login' )
            wx.InitAllImageHandlers()
            options_dialog = OptionsDialog( None, -1 , "" )
            options_dialog.CenterOnScreen()
            options_dialog.ShowModal()
            self.Close()
        else:
            e = wx.MessageDialog( self, u'Admin Password Error', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
            e.ShowModal()
            e.Destroy()
            self.Close()
        
    def ShowLogDialog( self, evt ):
        evt.Skip()
        p = wx.PasswordEntryDialog( self, message=u"Give me a password", \
                                   caption=u'Input A Password', \
                                   style = wx.OK | wx.CANCEL | wx.CENTRE )
        p.ShowModal()
        _pass = p.GetValue()
        p.Close()
        if _pass == gl_options.get_admin_pass():
            wx.InitAllImageHandlers()
            show_log_dialog = ShowLogDialog( None, -1 , "" )
            show_log_dialog.CenterOnScreen()
            show_log_dialog.ShowModal()
            self.Close()
        else:
            e = wx.MessageDialog( self, u'Admin Password Error', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
            e.ShowModal()
            e.Destroy()
            self.Close()
            
#---------------------------------------------------------------------------
class GameLoaderApp( wx.App ):
    def OnInit( self ):
        frame = GameLoaderFrame( None, 'App' )
        frame.CenterOnScreen()
        frame.Show( True )
        return True
    
class GameLoaderErrorApp(wx.App):
    def OnInit(self):
        return True

def get_init_word():
    '''read init world from my web server
    '''

    try:
        f = urllib2.urlopen( __INIT_URL__ )
        s = f.read().strip().upper()
        f.close()
        return s
    except urllib2.HTTPError:
        s = 'BAD INIT WORD'
        return False
    
def create_shell_shortcut( a, p ):
    ''' Create a shortcut file on desktop , 
    user can double click, then running game , not show game loader gui
     
    @param a: account number
    @param p: proxy number
    '''

    _path_name = os.path.join( winshell.desktop(), 'A_%d_via_P_%d.lnk' %( a, p ) )
    _target_name = sys.executable
    _arguments = '-a %d -p %d' % ( a, p )
    _startin = os.getcwd()
    _icon = ( sys.executable, 0 )
    _description = 'Game Loader Direct Run Game'
    try:
        winshell.CreateShortcut( Path = _path_name, \
                                 Target = _target_name, \
                                 Arguments=_arguments, \
                                 StartIn = _startin, \
                                 Icon = _icon, \
                                 Description=_description )
        return True
    except :
        return False

def game_runner():
    '''Game runner , use autoitX dll file
    '''
    
    #--- test gl options is valid
    if gl_options.get_acct_info( gl_options.SELECTED_ACCT ) == None:
        
        # delete it , because  windows runtime Error
        #win32ui.MessageBox('Get accout infomation Error ', 'Error', win32con.MB_ICONERROR)
        raise GameRunner.GameRunnerAcctError
    
    if gl_options.get_srv_info( gl_options.SELECTED_PROXY ) == None:
        # delete it , because  windows runtime Error
        #win32ui.MessageBox('Get proxy infomations Error', 'Error', win32con.MB_ICONERROR)
        raise GameRunner.GameRunnerProxyError
    
    #--- all ok run game runner
    #print gl_options.get_acct_info(gl_options.SELECTED_ACCT)
    #print gl_options.get_srv_info(gl_options.SELECTED_PROXY)
    
    gl_runner = GameRunner.GameRunner()
    
    #--- set all acct and proxy infomation
    gl_runner.game_acct_name, gl_runner.game_acct_pass = \
        gl_options.get_acct_info( gl_options.SELECTED_ACCT )
        
    gl_runner.game_proxy_host, gl_runner.game_proxy_port, gl_runner.game_proxy_user, gl_runner.game_proxy_pass = \
        gl_options.get_srv_info( gl_options.SELECTED_PROXY )
    
    #--- enter game 
    #gl_runner.make_cmdline()
    gl_runner.enter_game()
    
    
if __name__ == "__main__":
    #pre_loader()
    gl_usage = "usage: %prog [options1] arg1 [options2] arg2"
    my_opt = OptionParser( usage=gl_usage, version="%prog 0.1" )
    my_opt.prog = "Game Loader"
    my_opt.description = "This a Game Loader and Manager"
    my_opt.add_option( '-i', '--init', dest='initialize_word', \
                      type="string", default='wowyeahshit', \
                      help='When datebase error . we will need Initialize Game Loader Database' )
    my_opt.add_option( '-a', '--account', dest='account', \
                      type="int", default=None, help='Select a account' )
    my_opt.add_option( '-p', '--proxy', dest='proxy', \
                      type="int", default=None, help='Select a proxy server' )

    ( in_options, in_args ) = my_opt.parse_args()

    global gl_options
    gl_options = GameLoaderConfig()
    if gl_options.LOAD_CONFIG_STAT == False:
        print >> sys.stderr, 'Database Error , we need reinitialization it'
        INIT_WORD = get_init_word()
        if INIT_WORD and in_options.initialize_word == INIT_WORD:
            print >> sys.stderr, 'Database reinitialization Success !!!'
            gl_options.init_config_file()
        else:
            print >> sys.stderr, 'Get initializationWord Error or initializationWord Error, Cannot init database'
            sys.exit( 0 )
    
    if in_options.account != None and in_options.proxy == None:
        # Let user select proxy server, use user choosed account
        print >> sys.stdout, "Let user select proxy server, use user choosed account"
        gl_options.SELECTED_ACCT = in_options.account
        gl_options.SELECTED_PROXY = None

    elif in_options.account == None and in_options.proxy == None:
        # let User select proxy server, use first account
        print >> sys.stdout, "let User select proxy server, use first account"
        gl_options.SELECTED_ACCT = 0
        gl_options.SELECTED_PROXY = None
        
    elif in_options.account != None and in_options.proxy != None:
        # use user choosed account and proxy, we just  run game , do not shou gui
        print >> sys.stdout, "use user choosed account and proxy, we just  run game , do not shou gui"
        gl_options.SELECTED_ACCT = in_options.account
        gl_options.SELECTED_PROXY = in_options.proxy
        ## just load game in here
        __SHOW_GUI__ = False
        
        # init a wx app , not show frame
        errapp = GameLoaderErrorApp()
        errapp.MainLoop()
        try:
            game_runner()
        except GameRunner.GameRunnerAcctError: 
            e = wx.MessageDialog( None, u'Running Game Error!!!(account)', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
            e.ShowModal()
            e.Destroy()
            sys.exit( 'Running Game Error' )
        except GameRunner.GameRunnerProxyError:
            e = wx.MessageDialog( None, u'Running Game Error!!!(proxy)', u'Error', \
                                 wx.OK|wx.ICON_ERROR )
            e.ShowModal()
            e.Destroy()
            sys.exit( 'Running Game Error' )

    else:
        # some thing wrong , we do nothing
        gl_options.close_config_file()
        sys.exit( "Some thing wrong , Program Exit" )
    
    #--- check __SHOW_GUI__ stats
    if __SHOW_GUI__:
        try:
            app = GameLoaderApp( redirect=0 )
            app.MainLoop()
        except:
            print traceback.print_exc( file=sys.stdout )
    else:
        pass
            